<template>
  <view class="history-page">
    <!-- 头部导航 -->
    <view class="page-header">
      <view class="back-button" @tap="goBack">
        <text class="iconfont">&#xe60f;</text>
      </view>
      <text class="page-title">健康记录</text>
    </view>
    
    <!-- 入住人选择器 -->
    <view class="resident-selector">
      <scroll-view class="selector-scroll" scroll-x="true" show-scrollbar="false">
        <view 
          class="resident-item" 
          v-for="(person, index) in residents" 
          :key="index"
          :class="{ 'active': currentResidentId === person.id }"
          @tap="switchResident(person)"
        >
          <image class="resident-avatar" :src="person.avatar || '../../image/R.jpg'" mode="aspectFill"></image>
          <text class="resident-name">{{ person.name }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 健康类型选项卡 -->
    <view class="health-tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in healthTabs" 
        :key="index"
        :class="{ 'active': currentType === tab.id }"
        @tap="switchTab(tab.id)"
      >
        <text class="tab-text">{{ tab.name }}</text>
      </view>
    </view>
    
    <!-- 健康记录列表 -->
    <scroll-view class="record-list" scroll-y="true" @scrolltolower="loadMoreRecords">
      <view class="empty-tip" v-if="records.length === 0">
        <image src="/static/images/empty-records.png" mode="aspectFit" class="empty-img"></image>
        <text class="tip-text">暂无健康记录</text>
      </view>
      
      <view class="list-content" v-else>
        <!-- 年份分组标题 -->
        <view class="date-group" v-for="(group, gIndex) in groupedRecords" :key="gIndex">
          <view class="group-title">
            <text class="year">{{ group.year }}</text>
          </view>
          
          <!-- 记录项 -->
          <view 
            class="record-item"
            v-for="(record, rIndex) in group.records"
            :key="rIndex"
            @tap="viewRecordDetail(record)"
          >
            <view class="record-date">
              <text class="date-value">{{ formatMonthDay(record.date) }}</text>
              <text class="date-time">{{ formatTime(record.date) }}</text>
            </view>
            <view class="record-content">
              <view class="record-values">
                <text class="primary-value">{{ record.value }}</text>
                <text class="unit">{{ getUnitByType(currentType) }}</text>
              </view>
              <view class="record-notes" v-if="record.notes">
                <text class="notes-text">{{ record.notes }}</text>
              </view>
            </view>
            <view class="record-status" :class="getStatusClass(record.status)">
              <text class="status-text">{{ getStatusText(record.status) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMoreRecords">
          <text class="loading-text">加载中...</text>
        </view>
        <view class="no-more" v-else-if="records.length > 0">
          <text class="no-more-text">没有更多记录了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';

// 接收页面参数
const props = defineProps({
  residentId: {
    type: [Number, String],
    default: 0
  },
  type: {
    type: String,
    default: 'bloodPressure'
  }
});

// 页面数据
const currentResidentId = ref(parseInt(props.residentId) || 0);
const currentType = ref(props.type || 'bloodPressure');
const records = ref([]);
const hasMoreRecords = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);

// 健康数据类型选项
const healthTabs = [
  { id: 'bloodPressure', name: '血压' },
  { id: 'bloodSugar', name: '血糖' },
  { id: 'bloodLipids', name: '血脂' },
  { id: 'uricAcid', name: '尿酸' }
];

// 模拟居民数据
const residents = ref([
  {
    id: 1,
    name: '张三',
    avatar: '../../image/R.jpg'
  },
  {
    id: 2,
    name: '李四',
    avatar: '../../image/R.jpg'
  }
]);

// 监听类型变化，重新加载数据
watch(currentType, () => {
  resetRecords();
  loadRecords();
});

// 监听选中居民变化，重新加载数据
watch(currentResidentId, () => {
  resetRecords();
  loadRecords();
});

// 重置记录列表
const resetRecords = () => {
  records.value = [];
  currentPage.value = 1;
  hasMoreRecords.value = false;
};

// 按年份分组记录
const groupedRecords = computed(() => {
  const groups = {};
  
  // 将记录按年份分组
  records.value.forEach(record => {
    const date = new Date(record.date);
    const year = date.getFullYear();
    
    if (!groups[year]) {
      groups[year] = {
        year,
        records: []
      };
    }
    
    groups[year].records.push(record);
  });
  
  // 转换为数组并排序
  return Object.values(groups).sort((a, b) => b.year - a.year);
});

// 页面加载时执行
onMounted(() => {
  loadRecords();
});

// 加载记录数据
const loadRecords = () => {
  // 实际项目中应当调用API获取数据
  // 这里使用模拟数据
  setTimeout(() => {
    const newRecords = generateMockRecords(currentType.value, currentResidentId.value, currentPage.value, pageSize.value);
    
    // 追加新记录
    records.value = [...records.value, ...newRecords];
    
    // 模拟是否有更多数据
    hasMoreRecords.value = currentPage.value < 3; // 最多模拟3页数据
    
    // 页码增加
    currentPage.value++;
  }, 500);
};

// 加载更多记录
const loadMoreRecords = () => {
  if (hasMoreRecords.value) {
    loadRecords();
  }
};

// 切换选项卡
const switchTab = (tabId) => {
  currentType.value = tabId;
};

// 切换居民
const switchResident = (person) => {
  currentResidentId.value = person.id;
};

// 查看记录详情
const viewRecordDetail = (record) => {
  uni.navigateTo({
    url: `/pages/health/record-detail?type=${currentType.value}&time=${record.date.getTime()}`
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 根据状态获取样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'normal':
      return 'status-normal';
    case 'warning':
      return 'status-warning';
    case 'danger':
      return 'status-danger';
    default:
      return '';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'normal':
      return '正常';
    case 'warning':
      return '偏高';
    case 'danger':
      return '异常';
    default:
      return '未知';
  }
};

// 根据类型获取单位
const getUnitByType = (type) => {
  switch (type) {
    case 'bloodPressure':
      return 'mmHg';
    case 'bloodSugar':
      return 'mmol/L';
    case 'bloodLipids':
      return 'mmol/L';
    case 'uricAcid':
      return 'μmol/L';
    default:
      return '';
  }
};

// 格式化日期为月-日
const formatMonthDay = (date) => {
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 格式化时间为时:分
const formatTime = (date) => {
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 生成模拟数据
const generateMockRecords = (type, residentId, page, pageSize) => {
  const records = [];
  const now = new Date();
  const statuses = ['normal', 'warning', 'danger'];
  
  // 生成随机记录
  for (let i = 0; i < pageSize; i++) {
    const recordDate = new Date(now);
    // 往前推几天
    recordDate.setDate(now.getDate() - ((page - 1) * pageSize + i));
    // 随机时间
    recordDate.setHours(Math.floor(Math.random() * 12) + 7);
    recordDate.setMinutes(Math.floor(Math.random() * 60));
    
    // 根据类型生成不同的数据
    let value, status;
    switch (type) {
      case 'bloodPressure':
        const systolic = Math.floor(Math.random() * 40) + 100; // 100-140
        const diastolic = Math.floor(Math.random() * 30) + 60; // 60-90
        value = `${systolic}/${diastolic}`;
        status = systolic > 130 || diastolic > 85 ? (systolic > 140 || diastolic > 90 ? 'danger' : 'warning') : 'normal';
        break;
      case 'bloodSugar':
        value = (Math.random() * 3 + 4).toFixed(1); // 4.0-7.0
        status = value > 6.1 ? (value > 7.0 ? 'danger' : 'warning') : 'normal';
        break;
      case 'bloodLipids':
        value = (Math.random() * 2 + 3.5).toFixed(1); // 3.5-5.5
        status = value > 4.8 ? (value > 5.2 ? 'danger' : 'warning') : 'normal';
        break;
      case 'uricAcid':
        value = Math.floor(Math.random() * 200 + 250); // 250-450
        status = value > 350 ? (value > 420 ? 'danger' : 'warning') : 'normal';
        break;
    }
    
    records.push({
      id: ((page - 1) * pageSize + i + 1),
      date: recordDate,
      value,
      status,
      notes: Math.random() > 0.7 ? '饭后测量' : '' // 30%的概率有备注
    });
  }
  
  return records;
};
</script>

<style lang="scss">
page {
  background-color: #f5f8f8;
  height: 100%;
}

.history-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  
  .page-header {
    padding: 15px 20px;
    background-color: #fff;
    display: flex;
    align-items: center;
    position: relative;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    .back-button {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      position: absolute;
      left: 15px;
      
      .iconfont {
        font-size: 22px;
        color: #2c7873;
      }
    }
    
    .page-title {
      flex: 1;
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      color: #2c7873;
    }
  }
  
  .resident-selector {
    background-color: #fff;
    padding: 12px 15px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    
    .selector-scroll {
      white-space: nowrap;
      
      .resident-item {
        display: inline-flex;
        flex-direction: column;
        align-items: center;
        margin-right: 20px;
        vertical-align: top;
        
        &:last-child {
          margin-right: 0;
        }
        
        .resident-avatar {
          width: 50px;
          height: 50px;
          border-radius: 25px;
          background-color: #f5f5f5;
          border: 2px solid rgba(195, 227, 227, 0.3);
          margin-bottom: 6px;
        }
        
        .resident-name {
          font-size: 13px;
          color: #2c7873;
        }
        
        &.active {
          .resident-avatar {
            border-color: #c3e3e3;
          }
          
          .resident-name {
            color: #2c7873;
            font-weight: 600;
          }
        }
      }
    }
  }
  
  .health-tabs {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 12px 0;
      position: relative;
      
      .tab-text {
        font-size: 14px;
        color: #2c7873;
      }
      
      &.active {
        .tab-text {
          color: #2c7873;
          font-weight: 600;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 20px;
          height: 3px;
          background-color: #2c7873;
          border-radius: 1.5px;
        }
      }
    }
  }
  
  .record-list {
    flex: 1;
    padding: 15px;
    box-sizing: border-box;
    height: 0; /* 重要：让flex-grow能够正常工作 */
    
    .empty-tip {
      padding: 40px 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .empty-img {
        width: 120px;
        height: 120px;
        margin-bottom: 10px;
      }
      
      .tip-text {
        font-size: 14px;
        color: #999;
      }
    }
    
    .list-content {
      .date-group {
        margin-bottom: 20px;
        
        .group-title {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          
          .year {
            font-size: 16px;
            font-weight: 600;
            color: #2c7873;
            background-color: #e8f4f2;
            padding: 4px 12px;
            border-radius: 15px;
          }
        }
        
        .record-item {
          display: flex;
          align-items: center;
          background-color: #fff;
          border-radius: 12px;
          padding: 15px;
          margin-bottom: 10px;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
          
          .record-date {
            width: 60px;
            text-align: center;
            margin-right: 15px;
            
            .date-value {
              font-size: 15px;
              font-weight: 600;
              color: #2c7873;
              display: block;
              margin-bottom: 4px;
            }
            
            .date-time {
              font-size: 12px;
              color: #6FB3B8;
            }
          }
          
          .record-content {
            flex: 1;
            
            .record-values {
              display: flex;
              align-items: baseline;
              margin-bottom: 4px;
              
              .primary-value {
                font-size: 18px;
                font-weight: 600;
                color: #2c7873;
              }
              
              .unit {
                font-size: 12px;
                color: #6FB3B8;
                margin-left: 4px;
              }
            }
            
            .record-notes {
              .notes-text {
                font-size: 12px;
                color: #999;
                padding: 2px 8px;
                background-color: #f5f5f5;
                border-radius: 10px;
              }
            }
          }
          
          .record-status {
            padding: 4px 10px;
            border-radius: 12px;
            
            .status-text {
              font-size: 12px;
              color: #fff;
            }
            
            &.status-normal {
              background-color: #c3e3e3;
            }
            
            &.status-warning {
              background-color: #f0a500;
            }
            
            &.status-danger {
              background-color: #e57373;
            }
          }
        }
      }
      
      .load-more, .no-more {
        text-align: center;
        padding: 15px 0;
        
        .loading-text, .no-more-text {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
}
</style> 